package com.andy.qhb.conf;

import java.util.HashSet;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.andy.qhb.game.GameUser;
import com.andy.qhb.game.GlobalHttp;
import com.andy.qhb.game.Room;
import com.andy.qhb.utils.GoConstant;

@WebListener
public class SessionListener implements HttpSessionListener {
	public static final Logger logger = LoggerFactory.getLogger(SessionListener.class);


	@Override
	public void sessionCreated(HttpSessionEvent event) {
		logger.info("---sessionCreated：{}----",event.getSession().getId());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) throws ClassCastException {
		logger.info("---sessionDestroyed----");
		HttpSession session = event.getSession();
		logger.info("deletedSessionId: " + session.getId());
		
		GameUser user = getUser(session);
		if(user != null) {
			Room room = user.getRoom();
			if(room != null) {
				logger.info("---room remove:{}----",user.getId());
				room.removeUser(user);
			}
		}
	}

	public GameUser getUser(HttpSession session){
		Long uid = (Long) session.getAttribute(GoConstant.USER_SESSION_KEY);
		if(uid == null){
			return null;
		}
		return GlobalHttp.getUser(uid);
	}
	
}
